<template>
  <div class="root-table">
    <div class="table-operations">
      <a-button @click="onAdd">添加</a-button>
      <!-- <a-button @click="onDels">删除</a-button> -->
      <a-button @click="onRefresh">刷新</a-button>
      <a-button @click="onAnalysis">统计</a-button>
      <a-row type="flex">
        <a-col :span="6" :order="4"><a-input-search placeholder="请输入标签" @search="onSearchName" enterButton /></a-col>
        <a-col :span="6" :order="3">
          <a-tree-select
            showSearch
            allowClear
            :treeNodeFilterProp="'title'"
            style="width:100%"
            :treeData="treeData"
            :value="classifyIds"
            @change="onChangeCategoryTree"
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            :showCheckedStrategy="SHOW_PARENT"
            placeholder="请选择图库分类"
          />
        </a-col>
        <a-col :span="6" :order="2"></a-col>
        <a-col :span="6" :order="1"></a-col>
      </a-row>
    </div>
    <a-table :columns="columns"
      :rowKey="record => record.id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
    >
      <template slot="source" slot-scope="sourceText, record">
        <a :href="record.link" target="view_window">{{sourceText}}</a>
      </template>
      <template slot="url" slot-scope="url, record">
        <a-avatar shape="square" :size="64" icon="user" :src="url"/>
        <a-avatar shape="square" :size="64" icon="user" :src="record.model1" v-if="record.model1"/>
        <a-avatar shape="square" :size="64" icon="user" :src="record.model2" v-if="record.model2"/>
        <a-avatar shape="square" :size="64" icon="user" :src="record.model3" v-if="record.model3"/>
        <a-avatar shape="square" :size="64" icon="user" :src="record.model4" v-if="record.model4"/>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a @click="onEdit(record)" href="javascript:;" v-if="!record.designEnd && hasAuthority(['chart-finding']) || hasAuthority(['*'])">编辑</a>
        <a @click="onDelete(record.id)" href="javascript:;" v-if="!record.designEnd && hasAuthority(['chart-finding']) || hasAuthority(['*'])">删除</a>
      </template>
    </a-table>
    <keep-alive>
    <chart-finding-record-add
      ref="collectionForm"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :data="record"
      @ok="handleOk"
      @cancel="handleCancel"/>
    </keep-alive>
    <keep-alive>
    <chart-analysis
      :title="titleForAnalysis"
      :visible="visibleForAnalysis"
      :confirmLoading="confirmLoadingForAnalysis"
      :data="{}"
      @ok="handleOkForAnalysis"
      @cancel="handleCancelForAnalysis"/>
    </keep-alive>
  </div>
</template>
<script>
import Vue from 'vue'
import serv from './ChartFindingRecordService'
import chartFindingRecordAdd from './ChartFindingRecordAdd'
import chartAnalysis from './ChartAnalysis'
import { TreeSelect, Button, Table, Col, Row, Input } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
Vue.component(Input.Search.name, Input.Search)
Vue.component(Row.name, Row)
Vue.component(Col.name, Col)
Vue.component(Table.name, Table)
Vue.component(Button.name, Button)
const columns = [{
//   title: '期号',
//   dataIndex: 'issueNumber',
//   sorter: true,
//   width: '10%'
// }, {
  title: '来源',
  dataIndex: 'sourceText',
  sorter: false,
  width: '10%',
  scopedSlots: { customRender: 'source' }
}, {
  title: '下载金额',
  dataIndex: 'amount',
  width: '10%'
// }, {
//   title: '产品类型',
//   dataIndex: 'typeText',
//   width: '10%'
}, {
  title: '版本号',
  dataIndex: 'imageStorageClassifyNames',
  width: '10%'
}, {
  title: '投票数',
  sorter: true,
  dataIndex: 'votes',
  width: '10%'
}, {
  title: '图',
  dataIndex: 'url',
  width: '30%',
  scopedSlots: { customRender: 'url' }
}, {
  title: '名称',
  dataIndex: 'name',
  width: '5%'
}, {
  title: '创建时间',
  sorter: true,
  dataIndex: 'createTime'
}, {
  title: 'operation',
  dataIndex: '',
  scopedSlots: { customRender: 'operation' }
}]

export default {
  components: {
    chartFindingRecordAdd,
    chartAnalysis
  },
  mounted () {
    this.getTree()
    this.fetch({
      size: this.pagination.pageSize,
      page: this.pagination.current
    })
  },
  data () {
    return {
      data: [],
      pagination: {
        pageSize: 5,
        current: 1
      },
      selectedRowKeys: [],
      loading: false,
      columns,
      page: {},

      title: '',
      visible: false,
      confirmLoading: false,
      record: {},

      titleForAnalysis: '',
      visibleForAnalysis: false,
      confirmLoadingForAnalysis: false,

      treeData: [],
      SHOW_PARENT,
      searchData: {}
    }
  },
  computed: {
    classifyIds: function () {
      return this.searchData.classifyId ? this.searchData.classifyId : []
    },
    name: function () {
      return this.searchData.name
    }
  },
  methods: {
    onAnalysis () {
      this.titleForAnalysis = '统计'
      this.visibleForAnalysis = true
      this.confirmLoadingForAnalysis = false
    },
    onAdd () {
      this.title = '添加备选图'
      this.record = {}
      this.visible = true
      this.confirmLoading = false
    },
    onDelete (id) {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要删除这个备选图吗',
        onOk () {
          return new Promise((resolve, reject) => {
            serv.delete(id).then(res => {
              if (res.data.code === 0) {
                const dataSource = [..._this.data]
                _this.data = dataSource.filter(item => item.id !== id)
                resolve()
              } else {
                resolve()
                _this.$message.error(res.data.msg)
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onEdit (record) {
      this.title = '编辑备选图'
      this.visible = true
      this.confirmLoading = false
      this.record = record
    },
    onDels () {
    },
    onRefresh () {
      this.pagination.current = 1
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current
      })
    },
    handleOkForAnalysis () {
      // this.confirmLoading = true
      this.visibleForAnalysis = false
    },
    handleCancelForAnalysis () {
      this.visibleForAnalysis = false
    },
    handleOk (models, classifyIds) {
      const form = this.$refs.collectionForm.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        let formData = new FormData()
        for (let key in values) {
          let value = values[key]
          if (value) formData.append(key, value.file ? value.file : value)
        }
        for (let key in models) {
          formData.append(key, models[key])
        }
        formData.append('classifyIds[]', classifyIds)
        this.confirmLoading = true
        let pageNum = formData.get('id') ? this.pagination.current : 1
        serv.save(formData).then(res => {
          this.confirmLoading = false
          if (res.data.code === 0) {
            form.resetFields()
            this.visible = false
            this.fetch({
              size: this.pagination.pageSize,
              page: pageNum
            })
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    handleCancel (e) {
      this.visible = false
      this.record = {}
    },
    onSearchName (value) {
      this.pagination.current = 1
      if (value) {
        this.searchData.name = value
      } else {
        delete this.searchData.name
      }
      this.searchData = {...this.searchData}
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current,
        ...this.searchData
      })
    },
    async getTree () {
      this.treeData = await serv.getTree()
    },
    onChangeCategoryTree (value) {
      if (value) {
        this.searchData.classifyId = value
      } else {
        delete this.searchData.classifyId
      }
      this.searchData = {...this.searchData}
      this.pagination.current = 1
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current,
        ...this.searchData
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      let params = {
        size: pagination.pageSize,
        page: pagination.current,
        ...filters,
        ...this.searchData
      }
      if (sorter.field) {
        params.sort = `${sorter.field},${sorter.order === 'ascend' ? 'asc' : 'desc'}`
      }
      this.fetch(params)
    },
    async fetch (params = {}) {
      this.loading = true
      if (!params.sort) params.sort = `createTime,desc`
      this.page = await serv.getPage(params)
      const pagination = { ...this.pagination }
      pagination.total = this.page.totalElements
      // pagination.current = this.page.pageable.pageNumber + 1
      // console.log(this.pagination)
      this.loading = false
      this.selectedRowKeys = []
      this.data = this.page.content
      for (let node of this.data) {
        node.sourceText = this.value2name('IMAGE_SOURCE', node.source)
        node.typeText = this.value2name('PRODUCT_TYPE', node.productType)
      }
      this.pagination = pagination
    }
  }
}
</script>

<style scoped>
.root-table {
  height: 100%;
}
.table-operations {
  margin-bottom: 16px;
}

.table-operations > button {
  margin-right: 8px;
}
</style>
